package tech.lixinlei.current.collectors.tomap.demo;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import tech.lixinlei.current.collectors.tomap.bo.Student;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ToMapDemo {

    public static void main(String[] args) {
//        toMap();
        filter();
    }

    private static void filter() {
        List<Student> students = prepareDateWithNullName();
        Map<Integer, Student> map = students
                .stream()
                .filter(s -> StringUtils.isNotBlank(s.getName()))
                .collect(Collectors.toMap(Student::getId, Function.identity()));
        print(map);
    }

    private static void toMap() {
        List<Student> students = prepareData();
        Map<Integer, Student> map = students.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
        print(map);
    }

    private static void print(Map<Integer, Student> students) {
        for (Map.Entry<Integer, Student> entry : students.entrySet()) {
            System.out.println(JSON.toJSONString(entry));
        }
    }

    private static List<Student> prepareData() {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student();
        s1.setAge(18);
        s1.setName("leilei");
        s1.setId(1);
        students.add(s1);

        Student s2 = new Student();
        s2.setId(2);
        s2.setName("hua");
        s2.setAge(20);
        students.add(s2);

        Student s3 = new Student();
        s3.setAge(30);
        s3.setName("fafa");
        s3.setId(3);
        students.add(s3);

        return students;
    }

    private static List<Student> prepareDateWithNullName() {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student();
        s1.setAge(18);
        s1.setName("leilei");
        s1.setId(1);
        students.add(s1);

        Student s2 = new Student();
        s2.setId(2);
        s2.setName("hua");
        s2.setAge(20);
        students.add(s2);

        Student s3 = new Student();
        s3.setAge(30);
        s3.setName(null);
        s3.setId(3);
        students.add(s3);

        return students;
    }

}
